<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use manniu\model\Base;

use think\Cache;

class AdminMenu extends Base
{

	private $ids = [];
	/**
	 * 顶级菜单id
	 *
	 * @return	array
	 */
    public function getTopId(){
    	$_data = $this->where('pid=0')->field('id')->order('id ASC')->select();
    	if (!$_data) {
			return NULL;
		}
		$data = array();
		foreach ($_data as $t) {
			$data[] = $t->id;
		}
		return $data;
    }

    /**
	 * 分组菜单id
	 *
	 * @return	array
	 */
	public function getLeftId() {

		$_data = $this->where('pid','in',$this->getTopId())->field('id')->order('id ASC')->select();
		if (!$_data) {
			return NULL;
		}

		$data = array();
		foreach ($_data as $t) {
			$data[] = $t->id;
		}

		return $data;
	}

	// 获取自己id和子id
	public function getId($id) {

		if (!$id) {
			return NULL;
		}

		$this->ids[$id] = (int)$id;

		$data = $this->where('pid', $id)->field('id')->select();
		if (!$data) {
			return NULL;
		}

		foreach ($data as $t) {
			$this->ids[$t->id] = $t->id;
			$this->getId($t->id);
		}
	}


	/**
	 * 添加菜单
	 * @param	array	$data	添加数据
	 */
	public function add($data) {
		if (!$data) {
			return NULL;
		}

		$uri = '/';
		isset($data['module']) && $uri.= strtolower($data['module']).'/';
		isset($data['class']) && $uri.= $data['class'].'/';
		isset($data['method']) && $uri.= strtolower($data['method']).'/';

		$this->data([
			'uri' => trim($uri, '/'),
			'param' => isset($data['param']) ? trim($data['param'], '/') : '',
			'pid' => $data['pid'],
			'name' => $data['name'],
			'icon' => $data['icon'],
			'hidden' => isset($data['hidden']) ? (int)$data['hidden'] : 0,
			'displayorder' => $data['displayorder'] ? (int)$data['displayorder'] : 0,
		]);
		$this->save();
	}

	/**
	 * 修改菜单
	 * @param	array	$data	修改数据
	 * @param	int 	$id 	数据id
	 */
	public function edit($data,$id) {
		if (!$data) {
			return NULL;
		}

		$uri = '/';
		isset($data['module']) && $uri.= strtolower($data['module']).'/';
		isset($data['class']) && $uri.= $data['class'].'/';
		isset($data['method']) && $uri.= strtolower($data['method']).'/';

		$this->save([
			'uri' => trim($uri, '/'),
			'param' => isset($data['param']) ? trim($data['param'], '/') : '',
			'pid' => $data['pid'],
			'name' => $data['name'],
			'icon' => $data['icon'],
			'hidden' => isset($data['hidden']) ? (int)$data['hidden'] : 0,
			'displayorder' => $data['displayorder'] ? (int)$data['displayorder'] : 0,
		],['id'=>(int)$id]);
	}

	/**
	 * 删除菜单
	 * @param	array	$ids	数据id数组
	 */
	public function del($ids) {

		$this->ids = array();

		if (is_array($ids)) {
			foreach ($ids as $id) {
				$this->getId($id);
			}
		} else {
			$this->getId($ids);
		}
		
		$this->ids && $this->where('id','in',$this->ids)->delete();

	}

	/**
	 * 父级菜单选择
	 *
	 * @param	intval	$level	级别
	 * @param	intval	$id		选中项id
	 * @param	intval	$name	select部分
	 * @return	string
	 */
	public function parentSelect($level, $id = NULL, $name = NULL) {

		$select = $name ? $name : '<select name="data[pid]" class="form-control">';

		switch ($level) {
			case 0: // 顶级菜单
				$select.= '<option value="0">顶级菜单</option>';
				break;
			case 1: // 分组菜单
				$topdata = $this->field('id,name')->where('pid','0')->select();
				foreach ($topdata as $t) {
					$select.= '<option value="'.$t->data['id'].'"'.($id == $t->data['id'] ? ' selected' : '').'>'.$t->data['name'].'</option>';
				}
				break;
			case 2: // 链接菜单
				$topdata = $this->field('id,name')->where('pid','0')->select();
				foreach ($topdata as $t) {
					$select.= '<optgroup label="'.$t->data['name'].'">';
					$linkdata = $this->field('id,name')->where('pid',$t->data['id'])->select();
					foreach ($linkdata as $c) {
						$select.= '<option value="'.$c->data['id'].'"'.($id == $c->data['id'] ? ' selected' : '').'>'.$c->data['name'].'</option>';
					}
					$select.= '</optgroup>';
				}
				break;
		}

		$select.= '</select>';

		return $select;
	}


	/**
     * 更新缓存
     */
    public function cache($is_link = 0){
        Cache::set('admin_menu',NULL);
        Cache::set('admin_link',NULL);
        $list = $link = [];
        $data = $this->where('hidden',0)->order('displayorder asc,id asc')->select();

        if ($data) {
            foreach ($data as $t) {
                $topuri = false;
                if ($t->data['pid'] == 0) {
                    $list[$t->data['id']] = $t->data;
                    $list[$t->data['id']]['left'] = [];
                    foreach ($data as $m) {
                        if ($m->data['pid'] == $t->data['id']) {
                            $list[$t['id']]['left'][$m->data['id']] = $m->data;
                            foreach ($data as $n) {
                                $n->data['pid'] == $m['id'] && $list[$t->data['id']]['left'][$m->data['id']]['link'][$n->data['id']] = $n->data;
                                if(isset($list[$t->data['id']]['left'][$m->data['id']]['link'][$n->data['id']]) && !$topuri && !empty($list[$t->data['id']]['left'])){
                                	$list[$t->data['id']]['uri'] = $list[$t->data['id']]['left'][$m->data['id']]['link'][$n->data['id']]['uri'];
                                    $topuri = true;
                                }
                            }
                        }
                    }
                }
                strlen($t->data['uri']) > 5 && $link[$t->data['uri']] = 1;
            }
            Cache::set('admin_menu',$list);
            Cache::set('admin_link',$link);
        } else {
            Cache::set('admin_menu',NULL);
            Cache::set('admin_link',NULL);
        }
    }
}